package icu.yougan.youganblogbackend.service.impl;

import icu.yougan.youganblogbackend.common.Result;
import icu.yougan.youganblogbackend.mapper.ArticleMapper;
import icu.yougan.youganblogbackend.model.Article;
import icu.yougan.youganblogbackend.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public Result<List<Article>> list() {
        List<Article> articles = articleMapper.selectList();
        return Result.success(articles);
    }

    @Override
    public Result<Article> getById(Integer id) {
        Article article = articleMapper.selectById(id);
        if (article == null) {
            return Result.fail("文章不存在");
        }
        // 增加浏览量
        articleMapper.incrementViewCount(id);
        return Result.success(article);
    }

    @Override
    public Result<List<Article>> getByCategoryId(Integer categoryId) {
        List<Article> articles = articleMapper.selectByCategoryId(categoryId);
        return Result.success(articles);
    }

    @Override
    public Result<Article> add(Article article) {
        articleMapper.insert(article);
        return Result.success("添加成功", article);
    }

    @Override
    public Result<Article> update(Article article) {
        Article existingArticle = articleMapper.selectById(article.getId());
        if (existingArticle == null) {
            return Result.fail("文章不存在");
        }
        articleMapper.update(article);
        return Result.success("更新成功", article);
    }

    @Override
    public Result<Boolean> delete(Integer id) {
        Article article = articleMapper.selectById(id);
        if (article == null) {
            return Result.fail("文章不存在");
        }
        articleMapper.deleteById(id);
        return Result.success(true);
    }
} 